import { apiClient } from './index'
import { getApiPath } from '@/constants/apiMock'
import type {
  LoginParams,
  LoginResponse,
  UserInfo,
  ChartDataParams,
  ChartDataResponse,
  PaginationParams,
  PaginationResponse,
  UploadResponse,
  DashboardStats,
  SystemLog,
  RealTimeData,
} from './types'

// 认证相关API
export const authAPI = {
  // 用户登录
  login: (params: LoginParams): Promise<LoginResponse> => {
    return apiClient.post('/auth/login', params)
  },

  // 用户登出
  logout: (): Promise<void> => {
    return apiClient.post('/auth/logout')
  },

  // 获取用户信息
  getUserInfo: (): Promise<UserInfo> => {
    return apiClient.get('/auth/user')
  },

  // 刷新token
  refreshToken: (refresh_token: string): Promise<LoginResponse> => {
    return apiClient.post('/auth/refresh', { refresh_token })
  },

  // 修改密码
  changePassword: (params: { old_password: string; new_password: string }): Promise<void> => {
    return apiClient.post('/auth/change-password', params)
  },
}

// 仪表盘相关API
export const dashboardAPI = {
  // 获取仪表盘统计数据
  getStats: (): Promise<DashboardStats> => {
    return apiClient.get('/dashboard/stats')
  },

  // 获取图表数据
  getChartData: (params: ChartDataParams): Promise<ChartDataResponse> => {
    return apiClient.get('/dashboard/chart-data', params)
  },

  // 获取实时数据
  getRealTimeData: (): Promise<RealTimeData> => {
    return apiClient.get('/dashboard/realtime')
  },
}

// 用户管理相关API
export const userAPI = {
  // 获取用户列表
  getUsers: (params: PaginationParams): Promise<PaginationResponse<UserInfo>> => {
    return apiClient.get('/users', params)
  },

  // 创建用户
  createUser: (params: Omit<UserInfo, 'id'>): Promise<UserInfo> => {
    return apiClient.post('/users', params)
  },

  // 更新用户
  updateUser: (id: number, params: Partial<UserInfo>): Promise<UserInfo> => {
    return apiClient.put(`/users/${id}`, params)
  },

  // 删除用户
  deleteUser: (id: number): Promise<void> => {
    return apiClient.delete(`/users/${id}`)
  },

  // 批量删除用户
  batchDeleteUsers: (ids: number[]): Promise<void> => {
    return apiClient.post('/users/batch-delete', { ids })
  },
}

// 系统设置相关API
export const systemAPI = {
  // 获取系统配置
  getConfig: (): Promise<Record<string, any>> => {
    return apiClient.get('/system/config')
  },

  // 更新系统配置
  updateConfig: (config: Record<string, any>): Promise<void> => {
    return apiClient.post('/system/config', config)
  },

  // 获取系统日志
  getLogs: (params: PaginationParams & { level?: string; module?: string }): Promise<PaginationResponse<SystemLog>> => {
    return apiClient.get('/system/logs', params)
  },

  // 清理系统缓存
  clearCache: (): Promise<void> => {
    return apiClient.post('/system/clear-cache')
  },
}

// 文件上传相关API
export const uploadAPI = {
  // 上传单个文件
  uploadFile: (file: File, onProgress?: (progress: number) => void): Promise<UploadResponse> => {
    return apiClient.upload('/upload/file', file, onProgress)
  },

  // 上传头像
  uploadAvatar: (
    file: File,
    onProgress?: (progress: number) => void
  ): Promise<{
    avatar_url: string
  }> => {
    return apiClient.upload('/upload/avatar', file, onProgress)
  },

  // 批量上传文件
  uploadFiles: (files: File[]): Promise<UploadResponse[]> => {
    const formData = new FormData()
    files.forEach((file, index) => {
      formData.append(`files[${index}]`, file)
    })

    return apiClient.post('/upload/files', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
  },
}

// 气象局业务相关API
export const weatherAPI = {
  // 单个场站每日预测
  getSingleStationDailyForecast: (params: {
    target_id?: string
    time?: string
    signId?: string
    model?: string
  }): Promise<{
    code: number
    msg: string
    data: Array<{
      sign_id: string
      forecastTimeDaily: string
      total_swddi_power: number
      total_wind_power: number
      total_swddi_etc: number
      total_wind_etc: number
      install_power: number
      total_speed5floor: number
    }>
  }> => {
    return apiClient.get(getApiPath('singleStationForecast'), params)
  },

  // 多个场站每日预测
  getMultiStationDailyForecast: (): Promise<Record<string, any>> => {
    const tempAPI = getApiPath('multiStationForecast')
    // console.log('多个场站每日预测', tempAPI)
    return apiClient.get(tempAPI)
  },

  // 获取25个场站的预报辐射数据
  getStationRadiationForecast: (params: {
    reftime: string
    points: Array<{
      stationNum?: string
      lon: number
      lat: number
    }>
  }): Promise<Record<string, any>> => {
    return apiClient.post(getApiPath('stationRadiation'), params)
  },

  // 飞戈爬取-实时数据历史记录
  getRealTimeDataHistory: (): Promise<Record<string, any>> => {
    return apiClient.get(getApiPath('realtimeHistory'))
  },

  // 公服中心风速数据站点反演
  getWindSpeedStationData: (params: {
    forecastTime: string
    dayTime: string
    level: string // 只能为10，75，100，120，150
  }): Promise<{
    code: number
    msg: string
    page: string
    rows: null
    ds: Array<{
      level: string
      forecastTime: string
      name: string
      value: number
    }>
  }> => {
    return apiClient.get(getApiPath('windSpeedData'), params)
  },

  // 桂冠获取Token
  getGuiguanToken: (params: { appKey?: string; appSecret?: string }): Promise<Record<string, any>> => {
    return apiClient.get(getApiPath('guiguanToken'), params)
  },
}

// 设置业务相关API (保持向后兼容)
export const businessAPI = {
  // 获取业务数据
  getBusinessData: (): Promise<Record<string, any>> => {
    return apiClient.get(getApiPath('multiStationForecast'))
  },

  // 更新业务数据
  updateBusinessData: (data: Record<string, any>): Promise<void> => {
    return apiClient.post('/business/data', data)
  },

  // 气象局相关API的别名引用
  weather: weatherAPI,
}

// 导出所有API
export default {
  auth: authAPI,
  dashboard: dashboardAPI,
  user: userAPI,
  system: systemAPI,
  upload: uploadAPI,
  business: businessAPI,
  weather: weatherAPI,
}
